<?php
App::uses('AppController', 'Controller');
/**
 * Sections Controller
 *
 * @property Section $Section
 * @property PaginatorComponent $Paginator
 */
App::import('Controller', 'PreinscriptionProcesses');
//App::import('Controller', 'Courses');


class SectionsController extends AppController {


	public $helpers = array('Form', 'Html');

	var $PreinscriptionProcesses;

	function beforeFilter() {
		$this->PreinscriptionProcesses =& new PreinscriptionProcessesController; /*Loads the class*/
		$this->PreinscriptionProcesses->constructClasses(); 
	}

/**
 * Components
 *
 * @var array
 */
	public $components = array('Session', 'Paginator');

	public $paginate = array(
		'limit' => 5, //se muestran 10 cursos en la vista de inicio de cursos
		'order' => array('Section.Course.name' => 'asc')		
	);


/**
 * index method
 *
 * @return void
 */
	public function index($processId = null) {
		if($this->request->is('get')){

			$this->Section->Course->recursive = 0;
			$cond = array('Section.preinscription_process_id' => $processId);
			$cursos = $this->paginate('Section', $cond);

			$rolProfesor = 2;

			for($i=0; $i<count($cursos); $i++){
				$cursos[$i]['CoursesCode'] =  $this->Section->Course->CoursesCode->find(
					'all', array(
						'conditions' => array(
							'CoursesCode.course_id' => $cursos[$i]['Course']['id']
						)
					)
				);
				$cursos[$i]['Scheduleoption'] = $this->Section->Scheduleoption->find(
					'all', array(
						'conditions' => array(
							'Scheduleoption.section_id' => $cursos[$i]['Section']['id']
						)
					)
				);
				$j = 0;

				foreach($cursos[$i]['Professor'] as $profesor){
					$cursos[$i]['User'][$j] = $this->Section->Professor->User->findById($profesor['user_id']);
					$j++;
				}
			}
			$this->set(compact('cursos'));
			$this->set('proceso', $this->Section->PreinscriptionProcess->findById($processId));
			$this->set('processId', $processId);
			
			
		}
	}


//Funcion donde se descarga el excel con los cursos
	public function download($processId = null){
		require_once '../Vendor/Excel/PHPExcel.php';

		//Obtencion de datos para el excel
		$cursos = $this->Section->find('all', array('conditions' => array('Section.preinscription_process_id' => $processId)));
		for($i=0; $i<count($cursos); $i++){
			$cursos[$i]['Code'] =  $this->Section->Course->Code->find(
					'all', array(
						'conditions' => array(
							'Code.course_id' => $cursos[$i]['Course']['id']
						)
					)
				);
				$cursos[$i]['SchedulesOption'] = $this->Section->SchedulesOption->find(
					'all', array(
						'conditions' => array(
							'SchedulesOption.section_id' => $cursos[$i]['Section']['id']
						)
					)
				);
		}

		// Crea un nuevo objeto PHPExcel
		$objPHPExcel = new PHPExcel();

		$name = 'ExcelConCursos';

		//establecer propiedades
		$objPHPExcel->getProperties()
		->setCreator('Cattivo')
		->setLastModifiedBy('Cattivo')
		->setTitle('CursosDescargados')
		->setSubject('cursosDownload')
		->setDescription('oferta de cursos')
		->setKeywords('Excel Office 2007 openxml php')
		->setCategory('ExcelDoc');

		//Agregamos la información

		$i = 4;
		$semestre = $cursos[0]['PreinscriptionProcess']['semester'];
		if($semestre == 0)
			$periodo = 'Otoño '.$cursos[0]['PreinscriptionProcess']['year'];
		elseif($semestre == 1)
			$periodo = 'Primavera '.$cursos[0]['PreinscriptionProcess']['year'];
		else
			$periodo = 'Verano '.$cursos[0]['PreinscriptionProcess']['year'];

		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'OFERTA DE CURSOS SEMESTRE '.$periodo);
		$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:N1');
		$objPHPExcel->getActiveSheet()->getStyle('A1:N1')->getAlignment()
		->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A3','CODIGO')
		->setCellValue('B3','EQUIVALENCIA')
		->setCellValue('C3','UD')
		->setCellValue('D3','CUPO')
		->setCellValue('E3','NOMBRE CURSO')
		->setCellValue('F3','PROFESOR')
		->setCellValue('G3','HORARIO CATEDRA')
		->setCellValue('H3','HORARIO AUXILIAR')
		->setCellValue('I3','REQUISITOS')
		->setCellValue('J3','SALA')
		->setCellValue('K3','EXAMEN')
		->setCellValue('L3','EVALUACION DOCENTE')
		->setCellValue('M3','COORDINADOR')
		->setCellValue('N3','OBSERVACIONES');
		$objPHPExcel->getActiveSheet()->getStyle('A3:N3')->getAlignment()
		->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


		foreach($cursos as $curso){
			if(sizeof($curso['Code'])>1)
				$code_old = $curso['Code'][1]['Code']['name'];
			else 
				$code_old = '';

			$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A'.$i,$curso['Code'][0]['Code']['name'].'-'.$curso['Section']['number'])
			->setCellValue('B'.$i,$code_old)
			->setCellValue('C'.$i,$curso['Course']['ud'])
			->setCellValue('D'.$i, '-cupo-')
			->setCellValue('E'.$i,$curso['Course']['name']);
			/*->setCellValue('A3',)
			->setCellValue('A3',)
			->setCellValue('A3',)
			->setCellValue('A3',)
			->setCellValue('A3',)
			->setCellValue('A3',);*/

			$i ++;
		}
		//ajustar ancho de celdas
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('M')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('N')->setAutoSize(true);

		$styleArray = array(
  			'borders' => array(
    			'allborders' => array(
      				'style' => PHPExcel_Style_Border::BORDER_THIN
    			)
  			)
		);

		$objPHPExcel->getActiveSheet()->getStyle('A3:N'.($i-1))->applyFromArray($styleArray);
		unset($styleArray);

		$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(80);

		//renombrar hoja
		//$objPHPExcel->getActiveSheet()->setTitle('Tecnologia Simple');

		//restablecer hoja activa
		$objPHPExcel->setActiveSheetIndex(0);

		//modificar encabezados de http para indicar envio de excel
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename='.$name.'.xlsx'); 
		header('Cache-Control: max-age=0');

		$objWrite = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWrite->save('php://output');
		

		$this->Session->setFlash('Documento descargado con exito');
		$this->redirect(array('action' => 'index'));

	}
	//agregar seccion cargadas desde excel
	/*public function addExcel($data){
		$this->Section->create();
		$this->Section->save($data);
	}*/
	//Agregado completo
	public function add($processId = null){
		$this->set('processId', $processId);
		$this->set('processOpen', $this->PreinscriptionProcesses->processOpen());
		$this->set('relaciones', array('Equivalente con', 'Simultánea')); 

		$this->set('courses', $this->Section->Course->find('list'));

		if($this->request->is('post')){
			$this->Section->create();
			$nSeccion = $this->Section->find('count', array('conditions' => array('course_id' => $this->request->data['Section']['Course'])));
			$this->request->data['Section']['section_number'] = $nSeccion+1;
			$this->request->data['Section']['course_id'] = $this->request->data['Section']['Course'];
			echo '<pre>';
			print_r($this->request->data);
			echo '</pre>';
			if($this->Section->save($this->request->data)){
				$this->Session->setFlash('Sección '.$this->request->data['Section']['section_number'].' agregada con exito.');
				$this->redirect(array('action' => 'viewProfessor', $this->Section->id));
			}			
		}

	}

	public function edit($seccionId = null, $procesoId = null){

		$this->Section->id = $seccionId;
		$this->set('relaciones', array('Equivalente con', 'Simultánea')); 
		$this->set('seccionId', $seccionId);
		$this->set('processId', $procesoId);
		$this->set('processOpen', $this->PreinscriptionProcesses->processOpen());

		if($this->request->is('get')){
			$this->request->data = $this->Section->read();

			$this->set('idCurso', $this->request->data['Section']['course_id']);

			$this->set('coursesCodes', $this->Section->Course->CoursesCode->find('list'));

			//CODIGO
			$this->set('codigo', $this->Section->Course->CoursesCode->findByCourseId($this->request->data['Section']['course_id']));

			//HORARIOS -----
			if(sizeof($this->request->data['Scheduleoption'])>0){
				$func = function($value) {
				    return explode(';', $value['schedule'])[0];
				};

				$func2 = function($value){
					$aux = explode(';', $value['schedule']);
					return (sizeof($aux)==1)?'':$aux[1];
				};			
				$this->set('horarios',array_map($func,$this->request->data['Scheduleoption']));
				$this->set('auxiliar', array_map($func2, $this->request->data['Scheduleoption'])[0]);

			}else{
				$this->set('horarios',array());
				$this->set('auxiliar', array());
			}
			

			//Profesores ------
			$i =0;
			$profesor = array();
			foreach($this->request->data['Professor'] as $profe){
				$usuario = $this->Section->Professor->User->findById($profe['user_id'])['User'];
				$profesor[$i] = $usuario['first_name'].' '.$usuario['last_name'];
				$i++;
			}			
			$this->set('profesores', $profesor);

			//Requisitos
			$this->set('requisitos', $this->__splitrequisites($this->request->data['Course']['requisite']));

			
			

			
		//}elseif($this->request->is('post')){//post

		}else{
			$this->request->data['Course']['id'] = $this->request->data['Section']['idCurso'];
			$this->set('idCurso', $this->request->data['Section']['idCurso']);
			if($this->Section->save($this->request->data)){
				if($this->Section->Course->save($this->request->data['Course']))
				{

					$this->request->data = $this->Section->read();
					//CODIGO
					$this->set('codigo', $this->Section->Course->CoursesCode->findByCourseId($this->request->data['Section']['course_id']));

					//HORARIOS -----
					$func = function($value) {
					    return explode(';', $value['schedule'])[0];
					};

					$func2 = function($value){
						$aux = explode(';', $value['schedule']);
						return (sizeof($aux)==1)?'':$aux[1];
					};			
					$this->set('horarios',array_map($func,$this->request->data['Scheduleoption']));
					$this->set('auxiliar', array_map($func2, $this->request->data['Scheduleoption'])[0]);

					//Profesores ------
					$i =0;
					$profesor = array();
					foreach($this->request->data['Professor'] as $profe){
						$usuario = $this->Section->Professor->User->findById($profe['user_id'])['User'];
						$profesor[$i] = $usuario['first_name'].' '.$usuario['last_name'];
					}			
					$this->set('profesores', $profesor);

					//Requisitos
					$this->set('requisitos', $this->__splitrequisites($this->request->data['Course']['requisite']));

					$this->Session->setFlash('Curso actualizado correctamente');
					
				}else
					$this->Session->setFlash('Error al actualizar curso');

				
			}else
				$this->Session->setFlash('Error al actualizar sección');
				
			}

	}

	/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->Section->id = $id;
		$processId = $this->Section->findById($this->Section->id)['Section']['preinscription_process_id'];
		if (!$this->Section->exists()) {
			throw new NotFoundException(__('Invalid section'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->Section->delete($id, true)) {
			$this->Session->setFlash(__('La sección ha sido borrada.'));
		} else {
			$this->Session->setFlash(__('La sección no puede ser borrada. Por favor, intentelo nuevamente.'));
		}
		return $this->redirect(array('action' => 'index', $processId));
	}


	public function viewProfessor($seccionId = null){
		$this->Section->id = $seccionId;
		$professors = $this->Section->Professor->find('all', array(
			'conditions' => array(
				'section_id' => $seccionId)));

		$seccion = $this->Section->findById($seccionId);

		if(sizeof($professors) > 0)
			$this->set('curso', $this->Section->Course->findById($professors[0]['Section']['course_id']));
		else{
			$this->set('curso', $this->Section->Course->findById($seccion['Section']['course_id']));
		}
			
		$this->set('seccion', $seccion);
		$this->set('profesores', $professors);
		$this->set('seccionId', $seccionId);



	}

	public function viewSchedule($seccionId = null){
		$this->Section->id = $seccionId;
		$schedules = $this->Section->Scheduleoption->find('all', array(
			'conditions' => array(
				'section_id' => $seccionId)));

		$seccion = $this->Section->findById($seccionId);

		if(sizeof($schedules) > 0)
			$this->set('curso', $this->Section->Course->findById($schedules[0]['Section']['course_id']));
		else{
			$this->set('curso', $this->Section->Course->findById($seccion['Section']['course_id']));
		}
		
		$this->set('seccion', $seccion);
		$this->set('horarios', $schedules);
		$this->set('seccionId', $seccionId);
	}




	public function __splitRequisites($requisites){
		$reqSimultaneos = explode(',', $requisites);
		$i = 0;
		foreach($reqSimultaneos as $reqSimultaneo){
			$reqSimultaneos[$i] = explode('/',$reqSimultaneo);
			$i++;
		}

		return $reqSimultaneos;
	}

	public function __mergeRequisites($requisites){

	}


	

	


}

?>
